<?php

class PostMapper extends AMapper
{
	protected static $self = NULL;
	public static function &get() { return parent::_get(__CLASS__); }
	protected static function &getSelf() { return self::$self; }
	protected static function setSelf($in_self) { self::$self = $in_self; }

	public function find($in_post_id)
	{
		$postdata = DBConn::selectRow(sprintf("SELECT * FROM posts WHERE id=%d;", $in_post_id));
		if(!$postdata)
			throw new FrameworkRecordNotFoundException('post');
		return $this->load($postdata);
	}

	public function insert($in_post)
	{
		return $this->automaticInsert($in_post);
	}

	public function update($in_post)
	{
		return $this->automaticUpdate($in_post);
	}

	public function findByDate($in_start=0, $in_limit=0)
	{
		$query = "SELECT * FROM posts WHERE draft=0 ORDER BY date_added DESC";
		if($in_start || $in_limit)
			$query .= " LIMIT " . $in_start . "," . $in_limit;
		$data = DBConn::selectAll($query);
		$posts = array();
		foreach($data as $row)
		{
			$posts[] = $this->load($row);
		}
		return $posts;
	}
	
	public function findBySearchTerm($term, $in_start=0, $in_limit=0)
	{
		$query = "SELECT * FROM posts WHERE draft=0 AND (title LIKE %s OR body LIKE %s) ORDER BY date_added DESC";
		if($in_start || $in_limit)
			$query .= " LIMIT " . $in_start . "," . $in_limit;
		$search = DBConn::quote('%' . $term . '%');
		$data = DBConn::selectAll(sprintf($query, $search, $search));
		$posts = array();
		foreach($data as $row)
		{
			$posts[] = $this->load($row);
		}
		return $posts;
	}
	

	public function findAllByDate($in_start=0, $in_limit=0)
	{
		$query = "SELECT * FROM posts ORDER BY date_added DESC";
		if($in_start || $in_limit)
			$query .= " LIMIT " . $in_start . "," . $in_limit;
		$data = DBConn::selectAll($query);
		$posts = array();
		foreach($data as $row)
		{
			$posts[] = $this->load($row);
		}
		return $posts;
	}

	public function &load($in_post_array)
	{
		$entity = substr(__CLASS__,0,-6);
		$post = new $entity($in_post_array);
		return $post;
	}
}

?>
